package bll

import (
	"context"
	"manager/auth"
	log "manager/collector/logger"
	"manager/utils"

	"manager/event"
	"manager/model"
	"manager/model/entity"
	"manager/store"
	"manager/store/postgres"
	"time"
)

type messageNotify struct {
	iMessageNotify store.IMessageNotify
}

var MessageNotify = &messageNotify{
	iMessageNotify: postgres.MessageNotify,
}

func (a *messageNotify) init() func() {
	return func() {}
}

func (a *messageNotify) onEvent(data *event.Data) {
	if data == nil || (data.Type != event.Event_Bind_Bike && data.Type != event.Event_UnBind_Bike) {
		return
	}
	log.Info("---------------- messageNotify onEvent data:", utils.ToJsonString(data))
	if data.Type == event.Event_Bind_Bike {
		obj := data.Data.(*event.BindBike)
		if obj == nil {
			return
		}

		// 获取车辆信息
		bikeInfo, err := CacheBike.GetBikeInfoById(obj.BikeId)
		if err != nil {
			return
		}

		// 创建通知
		err = a.Create(context.Background(), &model.MessageNotifyCreateRequest{
			UserId:      obj.UserId,
			EbikeId:     obj.BikeId,
			EbikeName:   bikeInfo.Name,
			MessageType: 3,
			Title:       bikeInfo.Name,
			Content:     "恭喜您成功绑定一辆新车辆",
			Flag:        0,
			Extend:      "",
			FrameCode:   bikeInfo.FrameCode,
			RelationId:  0,
		})
		if err != nil {
			log.Error("messageNotify onEvent Create error:", err)
		}
	}

	// 车辆解绑
	if data.Type == event.Event_UnBind_Bike {
		obj := data.Data.(*event.UnBindBike)
		if obj == nil {
			return
		}

		// 删除车辆相关消息
		a.Delete(context.Background(), &model.MessageNotifyDeleteRequest{
			EbikeId: obj.BikeId,
		})
	}
}

// Create 创建
func (a *messageNotify) Create(ctx context.Context, in *model.MessageNotifyCreateRequest) error {
	var (
		err error
	)

	// 构建创建现场数据
	c := buildMessageNotify(in)
	_, err = a.iMessageNotify.Create(ctx, c)
	return err
}

// Update 更新
func (a *messageNotify) Update(ctx context.Context, in *model.MessageNotifyUpdateRequest) error {
	var (
		dict = make(map[string]interface{})
	)

	updateAt := time.Now().Unix()
	in.UpdatedAt = &updateAt

	userId, _ := auth.ContextUserID(ctx)
	// 获取用户相关车辆ID 消息类型以用户ID过滤
	if in.MessageType != nil && *in.MessageType != 3 {
		bikeIds := UserEbike.GetManagerBikeIds(userId)
		if len(bikeIds) == 0 {
			return nil
		}

		in.EbikeIds = bikeIds
	}

	if in.MessageType != nil && *in.MessageType == 3 {
		in.UserId = &userId
	}

	if in.EbikeId != nil {
		dict["ebike_id"] = in.EbikeId
	}

	if in.EbikeName != nil {
		dict["ebike_name"] = in.EbikeName
	}

	if in.Title != nil {
		dict["title"] = in.Title
	}

	if in.Content != nil {
		dict["content"] = in.Content
	}

	if in.Flag != nil {
		dict["flag"] = in.Flag
	}

	if in.UpdatedAt != nil {
		dict["updated_at"] = in.UpdatedAt
	}

	// do other update here

	return a.iMessageNotify.Update(ctx, in, dict)
}

// Delete 删除
func (a *messageNotify) Delete(ctx context.Context, in *model.MessageNotifyDeleteRequest) error {
	if in.EbikeId > 0 {
		return postgres.GetDB(ctx).Where("ebike_id = ?", in.EbikeId).Delete(&entity.MessageNotify{}).Error
	}
	return a.iMessageNotify.Delete(ctx, in.Id)
}

// List 列表查询
func (a *messageNotify) List(ctx context.Context, in *model.MessageNotifyListRequest) (*model.MessageNotifyListResponse, error) {
	var (
		err   error
		total int
		list  []*entity.MessageNotify
		out   = &model.MessageNotifyListResponse{}
	)

	// 获取用户ID
	userId, _ := auth.ContextUserID(ctx)
	if in.MessageType != nil && *in.MessageType == 3 {
		in.UserId = userId
	}

	// 获取用户相关车辆ID
	if in.MessageType != nil && *in.MessageType != 3 {
		bikeIds := UserEbike.GetManagerBikeIds(userId)
		if len(bikeIds) == 0 {
			return out, nil
		}
		in.EbikeIds = bikeIds
	}

	// 构建查询条件
	if total, list, err = a.iMessageNotify.List(ctx, in); err != nil {
		return nil, err
	}

	out.Total = total
	out.List = model.MessageNotifysEntityToDto(list)
	return out, nil
}

// Find 列表查询
func (a *messageNotify) Find(ctx context.Context, in *model.MessageNotifyInfoRequest) (*model.MessageNotifyInfo, error) {
	var (
		err  error
		data *entity.MessageNotify
		out  = &model.MessageNotifyInfo{}
	)

	if data, err = a.iMessageNotify.Find(ctx, in); err != nil {
		return nil, err
	}

	out = model.MessageNotifyEntityToDto(data)
	return out, nil
}

// buildMessageNotify 构建创建数据现场
func buildMessageNotify(in *model.MessageNotifyCreateRequest) *entity.MessageNotify {
	// todo: check the entity is required
	return &entity.MessageNotify{

		EbikeId: in.EbikeId,

		EbikeName: in.EbikeName,

		MessageType: in.MessageType,

		Title: in.Title,

		Content: in.Content,

		Flag: in.Flag,

		RelationId: in.RelationId,

		Extend: in.Extend,

		UserId: in.UserId,

		FrameCode: in.FrameCode,

		CreatedAt: time.Now().Unix(),

		UpdatedAt: time.Now().Unix(),
	}
}
